const fs = require('fs-extra')
const chalk = require('chalk');
const path = require('path')
const inquirer = require('inquirer');
const downloadGitRepo = require('download-git-repo');

const { isEmptyFolder, gitDownloadURIGen, drawSplit } = require('../utils')
const tpls = require('../configs/tpls')
const printError = require('../utils/error-hanlder');
const resolver = require('../file-resolver')
const clg = require('../utils/consoler')

function init(argv) {
  const argvProjName = argv._[1]
  // 将参数或者当前目录作为项目名称
  const appName = argvProjName || path.basename(process.cwd())
  // 如果输入了app名称，作为dist目录，否则将当前目录作为dist
  const dist = argvProjName ? path.join(process.cwd(), appName) : process.cwd()

  try {

    if (!isEmptyFolder(dist)) {
      throw new Error(`「${appName}」目录中含有其他文件， 请检查后进行初始化`)
    }
    // 存在template参数进行文件流下载
    if (typeof argv.template === 'string' && argv.template !== '') {
      return downlaodTemplate({ repoPath: argv.template, distPath: dist, appName })
    }
    // 进行手动选项
    inquirer.prompt([
      {
        type: 'list',
        name: 'repoConfig',
        message: '请选择一个模板',
        choices: Object.entries(tpls).map(t => ({
          name: `${t[1].name}`,
          value: { repo: t[1].repo, tplType: t[0] }
        }))
      },
      {
        type: 'list',
        name: 'authType',
        message: '模板拉取需要凭证，请选择凭证类型',
        choices: [
          { name: 'git&账号 方式', value: 'account' },
          { name: 'ssh&ssh 方式', value: 'ssh' }
        ]
      },
    ]).then(({ repoConfig, authType }) => {
      clg.info('正在初始化项目...')

      const { repo, tplType } = repoConfig
      const repoPath = gitDownloadURIGen(authType, repo)
      downlaodTemplate({ repoPath, distPath: dist, appName }, () => {
        resolver(appName, dist, { tplType })
      })
    })
  } catch (error) {
    // 将catch的错误打印
    printError('init', error);
  }
}

function downlaodTemplate({ repoPath, distPath, appName }, completeCB) {

  downloadGitRepo(repoPath, distPath, { clone: true }, result => {
    // 完成后result为undefined
    !result && completeCB && completeCB(true)

    if (result) {
      // 下载失败，清空目录
      fs.emptyDirSync(distPath)
      return printError('init', result)
    }
    drawSplit(chalk.green.bold(`「${appName}」创建成功`))
  })
}

module.exports = init